package com.heima.test1;

class RedWarsRunnable implements Runnable {
    int num = 3;

    @Override
    public void run() {

        synchronized (this) {
            if (num == 0) {
                System.out.println(Thread.currentThread().getName() + "抱歉,红包已经被抢走");
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                num--;
                System.out.println("恭喜" + Thread.currentThread().getName() + ",抢到一个20元红包");
            }
        }
    }
}

public class RedWarsRunnableDemo {

    public static void main(String[] args) {
        // 创建实现了Runnable接口的子类对象
        RedWarsRunnable redWarsRunnable = new RedWarsRunnable();

        // 创建5个Thread对象，把第一步创建的对象作为Thread的构造方法参数传递过来
        Thread t1 = new Thread(redWarsRunnable, "黄蓉");
        Thread t2 = new Thread(redWarsRunnable, "郭靖");
        Thread t3 = new Thread(redWarsRunnable, "黄药师");
        Thread t4 = new Thread(redWarsRunnable, "周伯通");
        Thread t5 = new Thread(redWarsRunnable, "瑛姑");
        // 启动5个线程
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}